package com.dsmbase.corp.flow.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import com.dsmbase.corp.flow.domain.FlowNode;

@Component
public class FlowNodeDao {

	private JdbcTemplate jdbcTemplate;
	
	private static final String SELECT_BY_ID_SQL = "select id, name, flow_id, work_load from flow_node where id = ?";
	private static final String SELECT_BY_FLOWID_SQL = "select id, name, flow_id, work_load from flow_node where flow_id = ?";
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	public void setDataSource(DataSource ds) {
		dataSource = ds;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public FlowNode getFlowNodeById(int id) throws SQLException {
		Object[] params = new Object[] { id };
		FlowNode flowNode = null;
		try {
			flowNode = (FlowNode) jdbcTemplate.queryForObject(SELECT_BY_ID_SQL,
					params, new FlowNodeRowMapper());
		} catch (EmptyResultDataAccessException e) {
			throw new SQLException(e);
		}
		return flowNode;
	}

	public List<FlowNode> getAllFlowNodesByFlowId(int flowId) throws SQLException {
		Object[] params = new Object[] { flowId };
		List<FlowNode> flowNodeList = null;
		try {
			flowNodeList = jdbcTemplate.query(SELECT_BY_FLOWID_SQL, params, new FlowNodeRowMapper());
		} catch (DataAccessException e) {
			throw new SQLException(e);
		}
		return flowNodeList;
	}
	
	public class FlowNodeRowMapper implements RowMapper<FlowNode> {

		public FlowNode mapRow(ResultSet rs, int index) throws SQLException {
			FlowNode flowNode = new FlowNode(rs.getInt("id"), rs.getString("name"),
					rs.getInt("flow_id"), rs.getInt("work_load"));
			return flowNode;
		}

	}
	
}
